package com.fx.demo.common;

import sun.misc.BASE64Decoder;

import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;

/**
 * des:
 *
 * @author fxiao
 * @date 2020/12/16 18:25
 */
public class RsaTools {
    /**
     * 公钥字符转化成PublicKey对象
     * @param publicKeyStr
     * @return
     */
    public static PublicKey parsePubKey(String publicKeyStr) {
        PublicKey publicKey = null;
        try {
            java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec(
                    new BASE64Decoder().decodeBuffer(publicKeyStr));
            KeyFactory keyFactory;
            keyFactory = KeyFactory.getInstance("RSA");
            publicKey = keyFactory.generatePublic(bobPubKeySpec);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return publicKey;
    }

    /**
     * 私钥字符转化成PrivateKey对象
     * @param privateKeyStr
     * @return
     */
    public static PrivateKey parsePrivateKey(String privateKeyStr) {
        PrivateKey privateKey = null;
        PKCS8EncodedKeySpec priPKCS8;
        try {
            priPKCS8 = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(privateKeyStr));
            KeyFactory keyf = KeyFactory.getInstance("RSA");
            privateKey = keyf.generatePrivate(priPKCS8);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return privateKey;
    }

    /**
     * 获取rsa公钥、密钥对
     * @return
     */
    public static HashMap<String, String > getKey(){
        KeyPairGenerator key = null;
        try {
            key = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        key.initialize(1024);
        // 产生密钥对
        KeyPair keyPair = key.generateKeyPair();
        // 得到公钥
        PublicKey publicKey = keyPair.getPublic();
        // 得到私钥
        PrivateKey privateKey = keyPair.getPrivate();
        byte[] keyBytes=publicKey.getEncoded();
        byte[] keyBytes2=privateKey.getEncoded();
        //base64加密,方便以字符bai串存入数据库或文件
        String temp = new sun.misc.BASE64Encoder().encodeBuffer(keyBytes);
//        System.out.println("公钥"+temp);
        String temp2 = new sun.misc.BASE64Encoder().encodeBuffer(keyBytes2);
//        System.out.println("私钥"+temp2);
        HashMap<String, String > keyRs=new HashMap<String, String >();
        keyRs.put("privateKey", temp2);
        keyRs.put("publicKey", temp);
        return keyRs;
    }
}
